package com.csdj.mail.receiver;

import com.csdj.server.pojo.Employee;
import com.csdj.server.pojo.MailConstants;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.util.Date;

/**
 * @Author zyq
 * @Date 2023/1/30 22:28
 * @ClassName: MailReceiver
 * @Description: TODO
 * @Version 1.0
 */
@Component
public class MailReceiver {

    private static final Logger logger= LoggerFactory.getLogger(MailReceiver.class);

    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private MailProperties mailProperties;

    @Autowired
    private TemplateEngine templateEngine;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     *
     * @param message 消息
     * @param channel 信道
     *
     */
    @RabbitListener(queues = MailConstants.MAIL_QUEUE_NAME)
    public void handler(Message message, Channel channel){

        MimeMessage msg = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(msg);
        Employee employee = (Employee) message.getPayload();
        //获取到消息头
        MessageHeaders headers = message.getHeaders();
        //消息序号
        long tag = (long) headers.get(AmqpHeaders.DELIVERY_TAG);
        //获取消息Id
       // String msgId = (String)
        //       headers.get("spring_returned_message_correlation");
        String msgId="12345";
        HashOperations hashOperations = redisTemplate.opsForHash();

        //获取 redis中的消息 id 然后再判断是否存在
        if (hashOperations.entries("mail_log").containsKey(msgId)){

            logger.info("消息已被消费====>"+msgId);
            try {
                /**
                 * 手动确认信息
                 * tag 序列号
                 * multiple 是否多条
                 */
                channel.basicAck(tag,false);
                //消息 消费后 不再进行推送
                return;
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

        try {
            helper.setFrom(mailProperties.getUsername());
            helper.setTo(employee.getEmail());
            helper.setSubject("入职欢迎邮件");
            helper.setSentDate(new Date());
            Context context = new Context();
            context.setVariable("name",employee.getName());
            context.setVariable("posName",employee.getPosition().getName());
            context.setVariable("joblevelName",employee.getJoblevel().getName());
            context.setVariable("departmentName",employee.getDepartment().getName());
            String mail = templateEngine.process("mail", context);
            helper.setText(mail,true);
            javaMailSender.send(msg);
            //消息 存储到 redis数据库中
            hashOperations.put("mail_log",msgId,"ok");
            //存储之后 不进行多条确认
            channel.basicAck(tag,false);
        } catch (Exception e) {
            try {
                /**
                 * 如果消息 推送 失败  退回队列
                 * tag 序列号
                 * multiple 是否多条 false
                 * 是否退会队列 true
                 */
                channel.basicNack(tag,false,true);

            } catch (IOException ioException) {

                logger.error("邮件发送失败=====>{}", e.getMessage());
            }
            logger.error("邮件发送失败=====>{}", e.getMessage());
        }

    }

}
